const path = require('path');
const fs = require('fs');
const template = require('./template.json');
// const api = require('../../mock-server/config').api;
// files, servicePath
class Mock {
    constructor(options) {
        this.files = options.files;
        this.api = options.api;
        this.start = (req, res) => {
            res.writeHead(200, {'Content-Type': 'text/html;charset=utf-8'});

            const text = getApiFile(this.files, req.path);
            if (!text) {
                res.end(getErrorTemp(500, '未定义当前接口的返回内容'));
                return;
            }
            const context = JSON.parse(text);
            const isRightMethos = context.method === req.method;
            isRightMethos ? res.end(JSON.stringify(context.response)) : res.end(getErrorTemp(400, '不支持的请求方法'))
        }
    }
}

function getErrorTemp(code, msg) {
    const res = JSON.parse(JSON.stringify(template));
    res.code = code;
    res.success = false;
    res.message = msg;
    return JSON.stringify(res);
}

function getApiFile(files, p) {
    let content = '';
    try {
        content = fs.readFileSync(path.join(files, p), 'utf-8');
    } catch (e) {
        content = '';
    }
    return content;
}

// const mock = new Mock({
//     files: path.resolve('./', 'mock-server/response'),
//     api
// })
// mock.start({path: '/burialPoint/addBurialPointInformation.json'})
module.exports = Mock;
